package cn.yr.system.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.yr.common.core.domain.dto.SysUserDto;
import cn.yr.common.core.domain.entity.SysUser;
import cn.yr.common.core.domain.entity.SysUserRole;
import cn.yr.common.core.domain.vo.PageVo;
import cn.yr.common.core.manager.AuthUserManager;
import cn.yr.common.exception.ret.Ret;
import cn.yr.common.security.annotation.PreAuthorize;
import cn.yr.system.service.ILoginService;
import cn.yr.system.service.ISysUserRoleService;
import cn.yr.system.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 用户信息表
 *
 * @author Lang
 * @email 1102076808@qq.com
 * @date 2020-07-13 23:07:36
 */
@Slf4j
@RestController
@RequestMapping("/sysUser")
public class SysUserController {

	/**
	 * 系统用户
	 */
	@Resource
	private ISysUserService sysUserService;
	/**
	 * 权限
	 */
	@Resource
	private ILoginService loginService;

	@Resource
	private ISysUserRoleService sysUserRoleService;

	@Resource
	private AuthUserManager authUserManager;

	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@PreAuthorize(hasPermi = "system:user:list")
	public Ret list(@RequestBody PageVo<SysUser> pageVo) {
		Map<String, Object> params = pageVo.getParams();
		QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
		wrapper.orderByAsc("user_type");
		wrapper.orderByDesc("create_time");
		wrapper.like(ObjectUtil.isNotEmpty(params.get("userName")), "user_name", params.get("userName"));
		wrapper.like(ObjectUtil.isNotEmpty(params.get("nickName")), "nick_name", params.get("nickName"));
		wrapper.like(ObjectUtil.isNotEmpty(params.get("phone")), "phone", params.get("phone"));
		wrapper.eq(ObjectUtil.isNotEmpty(params.get("sex")), "sex", params.get("sex"));
		wrapper.eq(ObjectUtil.isNotEmpty(params.get("userType")), "user_type", params.get("userType"));
		PageVo<SysUser> pageSysUser = sysUserService.pageUser(pageVo, wrapper);
		return Ret.success(pageSysUser);
	}


	/**
	 * 信息
	 */
	@RequestMapping("/info/{userId}")
	@PreAuthorize(hasPermi = "system:user:info")
	public Ret info(@PathVariable("userId") Long userId) {
		SysUser sysUser = sysUserService.getById(userId);
		return Ret.success(sysUser);
	}

	/**
	 * 保存
	 */
	@RequestMapping("/add")
	@PreAuthorize(hasPermi = "system:user:add")
	public Ret save(@Validated @RequestBody SysUser sysUser) {
		sysUserService.save(sysUser);

		return Ret.success();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/edit")
	@PreAuthorize(hasPermi = "system:user:edit")
	public Ret update(@Validated @RequestBody SysUser sysUser) {
		sysUserService.updateById(sysUser);

		return Ret.success();
	}

	/**
	 * 删除
	 */
	@RequestMapping("/remove/{userIds}")
	@PreAuthorize(hasPermi = "system:user:remove")
	public Ret delete(@PathVariable Long[] userIds) {
		sysUserService.removeByIds(Arrays.asList(userIds));
		return Ret.success();
	}


	/**
	 * @description
	 * @author Lang
	 * @date 2020/7/18 0:16
	 */
	@PostMapping("/updateUserRole")
	@PreAuthorize(hasPermi = "system:user:role")
	public Ret updateUserRole(@RequestBody List<SysUserRole> sysUserRoles) {
		sysUserRoleService.updateUserRole(sysUserRoles);
		return Ret.success();
	}

	/**
	 * @Description 个人信息
	 * @author Lang
	 * @Date 2020/7/15 22:36
	 */
	@GetMapping("profile/info")
	@PreAuthorize(hasPermi = "system:user:profile")
	public Ret getProfile() {
		SysUserDto user = authUserManager.getUser();
		return Ret.success(user);
	}

	@RequestMapping("profile/edit")
	@PreAuthorize(hasPermi = "system:user:profile")
	public Ret profile(@Validated @RequestBody SysUser sysUser) {
		if (sysUserService.updateById(sysUser)) {
			loginService.updateUser(authUserManager.uid());
			return Ret.success();
		} else {
			return Ret.error("修改失败");
		}

	}

	@PostMapping("/profile/avatar")
	@PreAuthorize(hasPermi = "system:user:profile")
	public Ret uploadAvatar( MultipartFile avatarFile) throws IOException {
		//TODO
		String upload = "";
		//String upload = OssKit.upload(avatarFile.getBytes(), IdUtil.fastSimpleUUID()+".png");
		SysUser sysUser = new SysUser();
		sysUser.setUserId(authUserManager.uid());
		sysUser.setAvatar(upload);
		sysUserService.updateById(sysUser);
		loginService.updateUser(authUserManager.uid());
		return Ret.success(MapUtil.builder("imgUrl",upload).map());
	}

	@PreAuthorize(hasPermi = "system:user:profile")
	@PutMapping("/profile/updatePwd")
	public Ret updatePwd(String oldPassword, String newPassword) {
		SysUser user = authUserManager.getUser().getSysUser();
		String password = user.getPassword();
		oldPassword = loginService.generatePassword(oldPassword, user.getSalt());
		newPassword = loginService.generatePassword(newPassword, user.getSalt());
		if (!StrUtil.equals(oldPassword, password)) {
			return Ret.error("修改密码失败，旧密码错误");
		}
		if (StrUtil.equals(newPassword, password)) {
			return Ret.error("新密码不能与旧密码相同");
		}
		SysUser sysUser = new SysUser();
		sysUser.setUserId(user.getUserId());
		sysUser.setPassword(newPassword);
		if (sysUserService.updateById(sysUser)) {
			loginService.updateUser(authUserManager.uid());
			return Ret.success();
		}
		return Ret.error("修改密码异常，请联系管理员");
	}

}
